package org.hd.login.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.hd.authentication.Auth;
import org.hd.login.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 登陆控制器
 */
@RestController
//@CrossOrigin(allowCredentials = "true",originPatterns = {"http://127.0.0.1:8848","http://localhost:3000","http://192.168.3.58:3000"},allowedHeaders = {"satoken"})  //解决跨域问题
@RequestMapping("/user/")
public class LoginController {

    @Resource
    UserService userService;

    /**
     * 角色获取器
     */
    @Resource
    Auth auth;

    //获取公钥,将公钥发送给前端
    @PostMapping("getPublicKey")
    public SaResult getPublicKey(
            @RequestBody Map<String,String> map
    ) throws Exception {
        String publicKey = userService.getPublicKey(map.get("username"));
        if(null == publicKey){
            return SaResult.error("未找到公钥");
        }
        return new SaResult(200,"公钥已找到",publicKey);
    }

    /***
     * 登录验证
     * @return
     */
    @PostMapping("doLogin")
    public SaResult userLogin(
            @RequestBody Map<String,String> paraMap
    ) {

        //获取密码比对结果
        Map map = userService.compailPassword(paraMap.get("username"),paraMap.get("cipherText"));

        List<String> roleList = auth.getRoleList(map.get("userId"), StpUtil.getLoginType());
        //如果验证成功
        if("success".equals(map.get("flag"))){
            StpUtil.login(map.get("userId"));
            map.put("username",map.get("username"));
            map.put("tokenValue",StpUtil.getTokenInfo().getTokenValue());
            map.put("tokenName",StpUtil.getTokenInfo().getTokenName());
            map.put("roleList",roleList);
            return new SaResult(200,"登录成功",map);
        }
        return SaResult.error("用户验证失败");
    }

    /**
     * 查询登录状态
     * @return
     */
    @RequestMapping("isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    /**
     * 查询 Token 信息
     * @return
     */
    @RequestMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    /**
     * 注销登录
     * @return
     */
    @PostMapping("logout")
    public SaResult logout(){
        StpUtil.logout();
        return SaResult.ok("已注销");
    }
}
